package com.example.demo.information.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.account.entity.SysUser;
import com.example.demo.account.entity.SysUserRole;
import com.example.demo.account.service.UserRoleService;
import com.example.demo.account.service.UserService;
import com.example.demo.common.utils.Constant;
import com.example.demo.information.entity.Bjxx;
import com.example.demo.information.entity.School;
import com.example.demo.information.entity.info.AdminInfo;
import com.example.demo.information.entity.info.SchoolInfo;
import com.example.demo.information.service.BjxxService;
import com.example.demo.information.service.SchoolService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.Serializable;
import java.util.*;

import static org.springframework.data.repository.init.ResourceReader.Type.JSON;

/**
 * @author littlecar
 * @date 2020/3/11 14:15
 */
@Controller
public class SchoolController {

    @Autowired
    private SchoolService schoolService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private BjxxService bjxxService;

    @RequestMapping("/toSchool")
    public String toSchool() {
        return "information/school/schoolList";
    }

    @RequestMapping("/schoolList")
    @ResponseBody
    public Map<String, Object> schoolList(String school_name,Integer page,Integer limit) {
        Map<String, Object> map = new HashMap<>();
        List<SchoolInfo> sxhoolInfoList = new LinkedList<>();
        List<School> schoolList = new LinkedList<>();
        List<School> allSchoolList = new LinkedList<>();
        int pages = (page - 1) * limit;
        if (StringUtils.isNotEmpty(school_name)) {
            school_name = "%" + school_name + "%";
            schoolList = schoolService.findPageByNameLike(school_name,pages,limit);
            allSchoolList=schoolService.findByNameLike(school_name);
        } else {
            schoolList = schoolService.findPageAll(pages,limit);
            allSchoolList=schoolService.findAll();
        }
        for (School school :
                schoolList) {
            sxhoolInfoList.add(new SchoolInfo(school));
        }
        map.put("data", sxhoolInfoList);
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", allSchoolList.size());
        return map;
    }

    @RequestMapping("/toSchoolAdd")
    public String toSchoolAdd() {
        return "information/school/schoolAdd";
    }

    @RequestMapping("/toSchoolModify")
    public String toSchoolModify(Long id, ModelMap map) {
        if (null != id) {
            School school = schoolService.findById(id);
            List<SysUser> userList = userService.findUserBySchoolIdAndRoleId(id, Constant.XX_USER_ID);
            String admin_name = "";
            String admin_id = "";
            if (null != userList && userList.size()>0) {
                for (int i = 0; i < userList.size(); i++) {
                    if (i < userList.size() - 1) {
                        admin_name += userList.get(i).getName() + ",";
                        admin_id += userList.get(i).getId() + ",";
                    }else{
                        admin_name += userList.get(i).getName();
                        admin_id += userList.get(i).getId();
                    }
                }
            }
            map.put("school", school);
            map.put("admin_name", admin_name);
            map.put("admin_id", admin_id);
        }
        return "information/school/schoolModify";
    }

    @RequestMapping(value = "/getBjListOption", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String, Object> getBjListOption(@RequestParam("xxId") Long xxId) {
        Map<String, Object> map = new HashMap<>();
        Set<Bjxx> bjxxSet = new HashSet<>();
        if (xxId != null) {
            /*School school = schoolService.findById(xxId);
            if (school != null && school.getBjxxList() != null && !school.getBjxxList().isEmpty()) {
                bjxxSet = school.getBjxxList();
            }*/
            bjxxSet = bjxxService.findBySchoolId(xxId);
        }
        map.put("list", bjxxSet);
        return map;
    }

    @RequestMapping("/checkSchoolNameUnique")
    @ResponseBody
    public String checkSchoolNameUnique(@RequestParam("name") String name, @RequestParam("id") String id) {
        List<School> schoolLsit = null;
        if (StringUtils.equals("undefined", id) || StringUtils.isEmpty(id) || StringUtils.isBlank(id)) {
            schoolLsit = schoolService.findByName(name);
        } else {
            School school = schoolService.findById(Long.valueOf(id));
            if (school.getName().equals(name)) {
                return "false";
            } else {
                schoolLsit = schoolService.findByName(name);
            }
        }
        if (null != schoolLsit && schoolLsit.size() > 0) {
            return "true";
        }
        return "false";
    }

    @RequestMapping("/toSelectAdmin")
    public String toSelectAdmin(@RequestParam("admin_id") String admin_id, ModelMap map ) {
        map.put("admin_id", admin_id);
        return "information/school/selectAdmin";
    }

    @RequestMapping("/adminList")
    @ResponseBody
    public Map<String, Object> adminList(String admin_name, int page ,int limit) {
        Map<String, Object> map = Maps.newLinkedHashMap();
        int pages = (page-1)*limit;
        List<AdminInfo> adminInfoList= Lists.newArrayList();
        List<SysUser> adminList = Lists.newArrayList();
        List<SysUser> allAdminList = Lists.newArrayList();
        if (StringUtils.isNotEmpty(admin_name)) {
            admin_name = "%" + admin_name + "%";
            allAdminList = userService.findPageSchoolAdminByNameLike(admin_name, pages, limit);
            adminList = userService.findSchoolAdminByNameLike(admin_name);
        }else{
            allAdminList = userService.findPageAllSchoolAdmin(pages, limit);
            adminList = userService.findAllSchoolAdmin();
        }
        for (SysUser user :
                allAdminList) {
            adminInfoList.add(new AdminInfo(user));
        }
        map.put("data", adminInfoList);
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", adminList.size());
        return map;
    }

    @RequestMapping("/schoolAdd")
    @ResponseBody
    public String schoolAdd(School school,@RequestParam("admin_id")String admin_id) {
        try {
            Long id = school.getId();
            if (null == id) {//新增
                school.setSxm(String.valueOf(school.getArea()));
                schoolService.save(school);
                if (StringUtils.isNotEmpty(admin_id)) {
                    String[] ids = admin_id.split(",");
                    for (String id1 :
                            ids) {
                        //找到user_id=id1 and role_id=4 and school_id=null 的 userRole
                        SysUserRole userRole = userRoleService.findOneByUserIdAndRoleId(Long.valueOf(id1), Constant.XX_USER_ID);
                        System.out.println(userRole);
                        if (null ==userRole) {
                            SysUserRole s = new SysUserRole();
                            s.setUser_id(Long.valueOf(id1));
                            s.setRole_id(Constant.XX_USER_ID);
                            s.setSchool_id(school.getId());
                            userRoleService.save(s);
                        }else{
                            userRole.setSchool_id(school.getId());
                            userRoleService.save(userRole);
                        }
                    }
                }
            }else{//编辑
                School s = schoolService.findById(id);
                s.setName(school.getName());
                s.setShort_name(school.getShort_name());
                s.setProvince(school.getProvince());
                s.setProvince_name(school.getProvince_name());
                s.setCity(school.getCity());
                s.setCity_name(school.getCity_name());
                s.setArea(school.getArea());
                s.setArea_name(school.getArea_name());
                s.setSxm(String.valueOf(school.getArea()));
                s.setBz(school.getBz());
                s.setAdmin_name(school.getAdmin_name());
                List<Long> userIdList=userRoleService.findUserIdBySchoolIdAndRoleId(id, Constant.XX_USER_ID);
                String[] ids = admin_id.split(",");
                ArrayList<String> adminIds = Lists.newArrayList(ids);
                for (String id1 :
                        ids) {
                    if(!userIdList.contains(Long.valueOf(id1))){
                        SysUserRole userRole = userRoleService.findByUserIdAndRoleIdAndSchoolId(Long.valueOf(id1), Constant.XX_USER_ID, id);
                        if (null != userRole) {
                            continue;
                        }
                        //找到user_id=id1 and role_id=4 and school_id=null 的 userRole
                        SysUserRole userRole1 = userRoleService.findOneByUserIdAndRoleId(Long.valueOf(id1), Constant.XX_USER_ID);
                        if (null ==userRole1) {
                            SysUserRole s1 = new SysUserRole();
                            s1.setUser_id(Long.valueOf(id1));
                            s1.setRole_id(Constant.XX_USER_ID);
                            s1.setSchool_id(id);
                            userRoleService.save(s1);
                        }else{
                            userRole1.setSchool_id(id);
                            userRoleService.save(userRole1);
                        }
                    }
                }
                for (Long l :
                        userIdList) {
                    if (!adminIds.contains(String.valueOf(l))) {
                        userRoleService.deleteByUserIdAndRoleIdAndSchoolId(l, Constant.XX_USER_ID, id);
                    }
                }
                schoolService.save(s);
            }
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    @RequestMapping("/schoolDel")
    @ResponseBody
    public String schoolDel(String id) {
        try {
            if (StringUtils.isNotEmpty(id)) {
                String[] ids = id.split(",");
                for (String school_id :
                        ids) {
                    Set<Bjxx> bjxxList = bjxxService.findBySchoolId(Long.valueOf(school_id));
                    if (bjxxList !=null && bjxxList.size()>0){
                        return "isExistBj";
                    }
                    schoolService.deleteById(Long.valueOf(school_id));
                }
            }
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    @RequestMapping("/getXxxxBjxxTree")
    @ResponseBody
    public Map<String,Object> getXxxxBjxxTree(){
        return schoolService.getXxxxBjxxTree();
    }
}
